
package com.xuelangyun.form.sys.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.xuelangyun.form.common.redis.lock.annotation.RedisLockConfig;
import com.xuelangyun.form.common.utils.DesUtils;
import com.xuelangyun.form.common.utils.MD5Utils;
import com.xuelangyun.form.common.utils.R;
import com.xuelangyun.form.sys.entity.SysUserEntity;
import com.xuelangyun.form.sys.form.SysLoginForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.xuelangyun.form.sys.service.ISysCaptchaService;
import com.xuelangyun.form.sys.service.ISysUserService;
import com.xuelangyun.form.sys.service.ISysUserTokenService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * 认证模块
 *
 * @author weiqing.hk
 */
@RestController
@RequestMapping("/auth")
@Api(value = "用户授权认证", tags = "授权接口")
@Slf4j
public class AuthLoginController {

    @Autowired
    private ISysCaptchaService sysCaptchaService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserTokenService sysUserTokenService;


    @RedisLockConfig(key = "#id")
    @GetMapping("/testLock")
    public R<Object> testLock(String id) {
        System.out.println("我进来了111");
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("我结束了111");
        return R.ok().setData("success");
    }

    /**
     * 验证码
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        log.info("captcha , uuid:[{}]", uuid);

        //获取图片验证码
        BufferedImage image = sysCaptchaService.nextCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }


    /**
     * 验证码
     */
    @GetMapping("/captchaBase64")
    public R<String> captchaBase64(String uuid) throws ServletException, IOException {
        //获取图片验证码
        BufferedImage image = sysCaptchaService.nextCaptcha(uuid);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
        byte[] data = out.toByteArray();
        String base64 = Base64.getEncoder().encodeToString(data).trim();

        base64 = "data:image/jpg;base64," + base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return R.ok(String.class).setData(base64);
    }

    /**
     * 登录
     */
    @PostMapping("/account")
    public R<Object> login(@RequestBody SysLoginForm form) throws IOException {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }

        //用户信息
        SysUserEntity user = sysUserService.queryByUserNo(form.getUserNo());
        if (user == null) {
            return R.error("账号或密码不正确");
        }
        String dePass = DesUtils.desEncrypt(form.getPassword());

        // 密码还原
        // String dePass2 = RsaUtils.decryptByPrivateKey(user.getPassword());
        if (dePass == null) {
            return R.error("密码不正确");
        }

        //账号不存在、密码错误
        String pass = MD5Utils.md5Pass(dePass.trim(), user.getSalt());
      /*  if (StringUtils.isBlank(user.getPassword()) || !user.getPassword().equals(pass)) {
            return R.error("账号或密码不正确");
        }*/

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库
        String token = sysUserTokenService.createToken(user.getUserId());
        // 更新用户最后登录时间
        Date curr = new Date();
        SysUserEntity update = new SysUserEntity();
        update.setLastLoginTime(curr);
        update.setUserId(user.getUserId());

        sysUserService.updateById(update);
        SysUserEntity copyUser = new SysUserEntity();

        // 用户复制,然后密码置为空
        org.springframework.beans.BeanUtils.copyProperties(user, copyUser);
        copyUser.setPassword(null);
        JSONObject jo = new JSONObject();
        jo.put("token", token);
        jo.put("user", copyUser);

        return R.ok().setData(jo);
    }
}
